/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.jms.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import servicios.FachadaService;

/**
 *
 * @author Matias
 */
@WebServlet(name = "Servlet", urlPatterns = {"/Servlet"})
public class Servlet extends HttpServlet {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/RiskyRiverServer/FachadaService.wsdl")
    private FachadaService service;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            if(request.getParameter("usuarioIniciar") != null)
            {
                //Ver de que pagina viene de Iniciar o unirse
                String usuarioIniciar = request.getParameter("usuarioIniciar");  
                //Vengo de la pagina de IniciarPartida
                if(usuarioIniciar != null && !usuarioIniciar.equals(""))
                {
                    if(!this.existePartidaJuego())
                    {
                        //Ya existe partida abierta
                        if(this.existePartidaAbierta())
                        {
                            response.sendRedirect("Unirse.jsp");
                        }
                        else
                        {
                            //Usuario se esta uniendo
                            int nivel = Integer.parseInt(request.getParameter("nivel"));
                            String result = this.jugarPartida(request.getParameter("usuarioIniciar"), nivel);
                            String [] cadena = result.split(",");

                            HttpSession session = request.getSession();
                            session.setAttribute("idJugador", cadena[0]);
                            session.setAttribute("turno",cadena[1]);
                            session.setAttribute("barco",cadena[2]);
                            response.sendRedirect("Juego.jsp");
                        }
                    }
                    else
                    {
                        response.sendRedirect("Error.jsp");
                    }
                }
                else
                {
                    //Usuario se esta uniendo y no importa el nivel porque se esta uniendo
                    String result = this.jugarPartida(request.getParameter("usuarioUnirse"), 0);
                    String [] cadena = result.split(",");
                    HttpSession session = request.getSession();
                    session.setAttribute("idJugador", cadena[0]);
                    session.setAttribute("turno",cadena[1]);
                    session.setAttribute("barco",cadena[2]);
                    response.sendRedirect("Juego.jsp");
                }
            }
            else
            {
                //Usuario se esta uniendo y no importa el nivel porque se esta uniendo
                    String result = this.jugarPartida(request.getParameter("usuarioUnirse"), 1);
                    String [] cadena = result.split(",");
                    HttpSession session = request.getSession();
                    session.setAttribute("idJugador", cadena[0]);
                    session.setAttribute("turno",cadena[1]);
                    session.setAttribute("barco",cadena[2]);
                    response.sendRedirect("Juego.jsp");
            }
            
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Servlet</title>");            
            out.println("</head>");
            out.println("<body>");
            //out.println("<h1>Id jugador " + cadena[0] + "</h1>");
            //out.println("<h1>Turno " + Boolean.parseBoolean(cadena[1]) + "</h1>");
            out.println("</body>");
            out.println("</html>");
            
            /*
            request.setAttribute("error", "1");
            response.sendRedirect("Login.jsp");
            * */
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String jugarPartida(java.lang.String arg0, int arg1) {
        servicios.Fachada port = service.getFachadaPort();
        return port.jugarPartida(arg0, arg1);
    }

    private boolean existePartidaAbierta() {
        servicios.Fachada port = service.getFachadaPort();
        return port.existePartidaAbierta();
    }

    private boolean existePartidaJuego() {
        servicios.Fachada port = service.getFachadaPort();
        return port.existePartidaJuego();
    }
}
